export default {
  data() {
    return {
      deleteApi: undefined, //删除接口  必须被混合使用的组件覆盖
      updateApi: undefined //修改接口  必须被混合使用的组件覆盖
    }
  },
  methods: {
    // 保存成功 回调事件
    onSuccess(rec) {
      const { dataSource, pagination } = this
      const index = dataSource.findIndex(x => x.id === rec.id)
      if (index > -1) dataSource.splice(index, 1, rec)
      else {
        if (dataSource.length >= (pagination?.pageSize || 10)) {
          dataSource.pop() //删除最后一条数据
        }
        dataSource.unshift(rec) //开头添加一条数据
        pagination.total++
      }
    },
    // 删除
    onDelete(id, index) {
      if (!this.deleteApi) return
      this.loading = true
      const { $message } = this
      this.deleteApi(id)
        .then(res => {
          if (res) {
            this.dataSource.splice(index, 1)
            this.pagination.total--
            $message.success('删除成功')
          } else $message.error('删除失败')
        })
        .catch(err => {
          $message.error(err)
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 更改状态 启用/停用
    onChange(id, checked, key = 'status') {
      if (!this.updateApi) return
      this.loading = true
      const { dataSource, $message } = this
      const data = checked ? 1 : 0
      this.updateApi(id, data)
        .then(res => {
          if (res) {
            const index = dataSource.findIndex(x => x.id === id)
            if (index > -1) {
              const record = dataSource[index]
              Object.assign(record, { [key]: data })
              dataSource.splice(index, 1, record)
            }
            $message.success('修改成功')
          } else $message.error('修改失败')
        })
        .catch(err => {
          $message.error(err)
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 状态是否可以点击
    authDisabled(t, e = 'enable', d = 'disable') {
      const r = Boolean(t)
      return (!r && !this.$auth(e)) || (r && !this.$auth(d))
    }
  }
}
